//
//  CoinDataService.swift
//  Crypto
//
//  Created by DaleGuo on 2023/9/22.
//

import Combine
import Foundation
import SwiftUI

class CoinDataService {
    @Published var allCoins: [CoinModel] = []

    var coinSubscription: AnyCancellable? // 不放入set中，更加明确

    init() {
        getCoins()
    }

    func getCoins() {
        guard let url = URL(string: "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=250&page=1&sparkline=true&price_change_percentage=24h")
        else {
            return
        }

        // 如果不取消订阅，将会一直监听未来可能的数据，但我们知道不会有持续数据，所以要cancel
        // 抽离出网络访问URLSession的通用部分
        coinSubscription = NetWorkingManager.download(url: url)
            .decode(type: [CoinModel].self, decoder: JSONDecoder())
            .receive(on: DispatchQueue.main) // 🌟优化：decode又副线程完成
            .sink(receiveCompletion: NetWorkingManager.handleCompletion, receiveValue: { [weak self] returnedCoins in
                self?.allCoins = returnedCoins
                self?.coinSubscription?.cancel() // cancle sub
            })
//            .sink { completion in
//                //抽离通用部分completion到NetWorkingManager
//                switch completion { // 由于trymap可能throws 所以sink有多个completion
//                case .finished:
//                    break
//                case .failure(let error):
//                    print("Download data errow : \(error)")
//                }
//            } receiveValue: { [weak self] returnedCoins in
//                self?.allCoins = returnedCoins
//                self?.coinSubscription?.cancel() // cancle sub
    }
}
